//
//  StudyCourseNoteViewController.m
//  LovingPartyBuilding
//
//  Created by ZJ on 2017/5/4.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "StudyCourseNoteViewController.h"
#import "ZJSCNoteTableViewCell.h"
#import "ZJRefurbish.h"
#import "SendCommentView.h"
#import <IQKeyboardManager.h>
#define CellID  @"ZJSCNoteTableViewCell"
@interface StudyCourseNoteViewController ()<UITableViewDelegate,UITableViewDataSource,ZJSCNoteTableViewCellDelegate,SendCommentViewDelegate>
{
    
    UIView *_commentBGView;/** 评论页面背景View */
}
/** tableView */
@property (nonatomic, strong) UITableView *tableView;
/** dataArray */
@property (nonatomic, strong) NSMutableArray *dataArray;
/**  分页  */
@property (assign, nonatomic) NSInteger  page;
/** 刷新页面 */
@property (nonatomic, strong) ZJRefurbish *refurbish;
/** 评论模块 */
@property (nonatomic, strong) SendCommentView *sendCommentView;
/** 评论输入框 */
@property (nonatomic, strong) UIButton *commentTextButton;

@end

@implementation StudyCourseNoteViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    if (self.block) {
        self.block();
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor viewBGGrayColor];
    __weak typeof(self) weakSelf = self;
    [self.refurbish headerToScollview:self.tableView Block:^{
        weakSelf.page = 1;
        [weakSelf netWorking_header];
    }];
    [self.refurbish footerToScollview:self.tableView Block:^{
        weakSelf.page ++;
        [weakSelf netWorking_footer];
    }];
    [self setupUI];
    [self.tableView.mj_header beginRefreshing];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */

}


- (void)setupUI{
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.commentTextButton];
    
    _commentBGView = [[UIView alloc] initWithFrame:self.view.bounds];
    _commentBGView.backgroundColor = [UIColor blackColor];
    _commentBGView.alpha = 0.2;
    _commentBGView.hidden = YES;
    UITapGestureRecognizer *tapGester = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action_tapGester)];
    [_commentBGView addGestureRecognizer:tapGester];
    [self.view addSubview:_commentBGView];
    [self.view addSubview:self.sendCommentView];
    
}

- (void)netWorking_header{

    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"USER_ID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,
                           @"COURSEWARE_ID":self.model.ID,
                           @"PAGE_NUMBER":[NSString stringWithFormat:@"%ld",_page],
                           @"SHOW_NUMBER":@"10"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL listCourseNote] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//
            weakSelf.dataArray = [[NSArray yy_modelArrayWithClass:[ZJSCNoteModel class] json:object[@"NOTES"]] mutableCopy];
            [weakSelf.tableView reloadData];
        }
        [weakSelf.tableView.mj_header endRefreshing];
    } Fail:^(id object) {
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
- (void)netWorking_footer{
    
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"USER_ID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,
                           @"COURSEWARE_ID":self.model.ID,
                           @"PAGE_NUMBER":[NSString stringWithFormat:@"%ld",_page],
                           @"SHOW_NUMBER":@"10"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL listCourseNote] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZJSCNoteModel class] json:object[@"NOTES"]] ;
            [weakSelf.dataArray addObjectsFromArray:array];
            [weakSelf.tableView reloadData];
        }
        [weakSelf.tableView.mj_footer endRefreshing];
    } Fail:^(id object) {
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}


#pragma mark - 键盘处理

- (void)action_tapGester{
    [self.view endEditing:YES];
    
}

- (void)keyboardWillShow:(NSNotification *)notification {
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    
    _commentBGView.hidden = NO;
    self.sendCommentView.hidden = NO;
    [self.view bringSubviewToFront:self.sendCommentView];
    
    CGFloat curkeyBoardHeight = [[[notification userInfo] objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - weakSelf.sendCommentView.height - curkeyBoardHeight, [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
    }];
}

- (void)keyboardWillDismiss:(NSNotification *)notification {
    _commentBGView.hidden = YES;
    self.sendCommentView.hidden = YES;
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
        
    }];
}

#pragma mark - 下部评论点击按钮
- (void)action_commentTextButton:(UIButton *)sender{
    [self.sendCommentView.commentTextView.textView becomeFirstResponder];
}


#pragma mark - ZJSCNoteTableViewCellDelegate 协议方法
//删除
- (void)ZJSCNoteTableViewCellDelegate_DeleteButton:(ZJSCNoteModel *)model{
    [self.dataArray removeObject:model];
    [self.tableView reloadData];
}


#pragma mark - SendCommentViewDelegate 协议方法
//发送评论
- (void)sendButtonClick{
    [self.view endEditing:YES];
    [self netWorkingNote];
}
//笔记
- (void)netWorkingNote{
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"USER_ID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,//用户id
                           @"VIDEO_STAMP":@(self.currTime),//视频时间
                           @"COURSEWARE_ID":self.model.ID,//课程id
                           @"UNITID":[ZJUserInfoModel sharedUserInfo].DEPT_MODEL_JOB.ID,//机构id
                           @"NOTE_CONTENT":self.sendCommentView.commentTextView.textView.text};//笔记内容
    [NetWorkingManager postWithUrlString:[NetWorkingURL courseNote] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        [YJProgressHUD hide];
        if ([model.STATE isEqualToString:@"20000"]) {//记笔记成功
            [weakSelf.tableView.mj_header beginRefreshing];;
        }else{
            [YJProgressHUD showMsgWithoutView:@"记笔记失败"];
        }
    } Fail:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"记笔记失败"];
    }];
    
}





#pragma mark - UITableView 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZJSCNoteModel *model = self.dataArray[indexPath.row];
    ZJSCNoteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
    cell.model = model;
    cell.delegate = self;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZJSCNoteModel *model = self.dataArray[indexPath.row];
    return model.cellHeight;
}



#pragma mark - Setter


#pragma mark - Getters
- (UITableView *)tableView{
    if (_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height - LP_TopHeight - 49) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 7.5 * [UIScreen zj_screenHScale])];
        view.backgroundColor = [UIColor viewBGGrayColor];
        _tableView.tableHeaderView = view;
        [_tableView  registerClass:[ZJSCNoteTableViewCell class] forCellReuseIdentifier: CellID];
        
    }
    return _tableView;
}

- (NSMutableArray *)dataArray{
    if (_dataArray == nil){
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}

- (ZJRefurbish *)refurbish{
    if (_refurbish == nil){
        _refurbish = [ZJRefurbish new];
    }
    return _refurbish;
}

- (SendCommentView *)sendCommentView{
    if (_sendCommentView == nil){
        _sendCommentView = [[SendCommentView alloc]initWithFrame:CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], [UIScreen zj_screenHeight] * 0.2)];
        _sendCommentView.commentDelegate = self;
    }
    return _sendCommentView;
}

- (UIButton *)commentTextButton{
    if (_commentTextButton == nil){
        _commentTextButton = [[UIButton alloc]initWithFrame:CGRectMake(18 * [UIScreen zj_screenWScale],self.tableView.bottom + 10, self.view.width - 36 * [UIScreen zj_screenWScale], 29)];
        _commentTextButton.backgroundColor = [UIColor zj_colorWithHexString:@"f3f3f3"];
        _commentTextButton.layer.cornerRadius = 8 ;
        _commentTextButton.titleLabel.font = [UIFont systemFontOfSize:14 * [UIScreen zj_textFontScale]];
        [_commentTextButton setTitle:@"期待您的评论" forState:UIControlStateNormal];
        [_commentTextButton setTitleColor:[UIColor zj_colorWithHexString:@"777777"] forState:UIControlStateNormal];
        [_commentTextButton addTarget:self action:@selector(action_commentTextButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commentTextButton;
}
@end
